﻿using AutoMapper;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 系统日志(Ok)
    /// </summary>
    public class SystemController : BaseController<SystemController>
    {
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmSystemLog> _systemLogRepository;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        /// <param name="cacheProvider"></param>
        /// <param name="dbContext"></param>
        /// <param name="systemLogRepository"></param>
        public SystemController(IRepository<ZmUser> userRepository
            , ILogger<SystemController> logger
            , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
            , IRepository<ZmSystemLog> systemLogRepository) : base(logger, systemLogRepository)
        {
            _cache = cacheProvider.CreateCache();
            _mapper = mapper;
            _dbContext = dbContext;
            _userRepository = userRepository;
            _systemLogRepository = systemLogRepository;
        }

        /// <summary>
        /// 获取系统日志信息列表
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("system/logs/list")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<SystemLogDto>>), 200)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<Page<SystemLogDto>> ListTemplates([FromQuery] DatePageRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<SystemLogDto>>(false, "PageIndex must >= 0");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<Page<SystemLogDto>>(false, "user not logined");
            }

            var logs = (from log in _dbContext.ZmSystemLog
                        where log.IsDelete != 1
                        select _mapper.Map<SystemLogDto>(log))
                            .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
            return new RespRet<Page<SystemLogDto>>(true, "Ok", logs);
        }
    }
}
